package com.haoshuang.zhouzhoubang.ui.page.shop.order

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.alipay.sdk.app.PayTask
import com.haoshuang.zhouzhoubang.config.Config
import com.haoshuang.zhouzhoubang.databinding.ActivityShopOrderBinding
import com.haoshuang.zhouzhoubang.ui.adapter.ViewPagerAdapter
import com.haoshuang.zhouzhoubang.ui.dialog.PayDialog
import com.haoshuang.zhouzhoubang.ui.page.shop.order.child.OrderListShopFragment
import com.haoshuang.zhouzhoubang.utils.Event
import com.haoshuang.zhouzhoubang.utils.PayResult
import com.haoshuang.zhouzhoubang.utils.PaymentUtil
import com.haoshuang.zhouzhoubang.utils.PreferenceUtils
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 *  商城订单
 */
class ShopOrderActivity : BaseVMActivity<ShopOrderViewModel, ActivityShopOrderBinding>() {

    override fun initView(savedInstanceState: Bundle?) {
        binding.appBar.ivBack.click { finish() }
        binding.appBar.tvTitle.text = "商品订单"
    }

    private val mFragments = ArrayList<Fragment>()  //存放学习子界面的Fragment集合

    override fun initData() {
        EventBus.getDefault().register(this)
        val type = intent.getIntExtra("type", 0)
        mFragments.clear()
        mFragments.add(OrderListShopFragment.getInstance(-1))
        mFragments.add(OrderListShopFragment.getInstance(0))
        mFragments.add(OrderListShopFragment.getInstance(1))
        mFragments.add(OrderListShopFragment.getInstance(2))
        mFragments.add(OrderListShopFragment.getInstance(3))


        val mAdapter = ViewPagerAdapter(supportFragmentManager, lifecycle, mFragments)
        //  mAdapter = MyPagerAdapter2(parentFragmentManager,mFragments,mTitles88)
        binding.vpOrder.adapter = mAdapter
        binding.slidingTabLayout.setViewPager2(
            binding.vpOrder,
            arrayListOf("全部", "待付款", "待发货", "待收货", "已完成")
        )
        binding.vpOrder.offscreenPageLimit = 5
        binding.vpOrder.currentItem = type
        binding.vpOrder.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                num9 = position
                (mFragments[position] as OrderListShopFragment).updata()
            }
        })
    }

    var num9 = 0
    override fun startObserve() {
        vm.getData2.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                payAlipay(this@ShopOrderActivity, it?.body!!)
            }
        }
        vm.getData3.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                var api = WXAPIFactory.createWXAPI(this@ShopOrderActivity, Config.WX_ID, false)
                PreferenceUtils.putString("Wxpay", "2")
                PaymentUtil.payWxPayment(api, it)
            }
        }
    }

    //订阅方法，当接收到事件的时候，会调用该方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageEvent: Event) {

        if (messageEvent.code == 8004) {
            toast("支付成功")
            // startPage<SuccessActivity>()
            if (num9 == 1) {
                (mFragments[1] as OrderListShopFragment).updata()
            } else {
                (mFragments[0] as OrderListShopFragment).updata()
            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    private val SDK_PAY_FLAG = 1

    @SuppressLint("HandlerLeak")
    var mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    val payResult = PayResult(msg.obj as Map<String?, String?>)

                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo = payResult.result // 同步返回需要验证的信息
                    val resultStatus = payResult.resultStatus
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        toast("支付成功")
                        // startPage<SuccessActivity>()
                        if (num9 == 1) {
                            (mFragments[1] as OrderListShopFragment).updata()
                        } else {
                            (mFragments[0] as OrderListShopFragment).updata()
                        }

                    } else {
                        toast("支付失败")

                    }
                }

                else -> {}
            }
        }
    }

    fun payAlipay(mContext: Context?, orderNo: String) {
        val payRunnable = Runnable {
            val alipay = PayTask(mContext as Activity?)
            val result = alipay.payV2(orderNo, true)
            val msg = Message()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            mHandler.sendMessage(msg)
        }
        // 必须异步调用
        val payThread = Thread(payRunnable)
        payThread.start()
    }

    fun Pay(id: Int) {
        XPopup.Builder(this@ShopOrderActivity)
            .dismissOnTouchOutside(false)
            .asCustom(PayDialog(this@ShopOrderActivity) {
                if (it == 1) {
                    vm.getData3(
                        "id" to id, "payType" to it
                    )
                } else {
                    vm.getData2(
                        "id" to id, "payType" to it
                    )
                }

            })
            .show()
    }

}